﻿using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Linq;
using System.Text;


namespace Mattress.Engine.Matlab {
    internal class mxCharArray : mxArray {
        public mxCharArray(SafeArrayPtr pa) : base(pa, mxArrayType.Char) { }

        public mxCharArray(string value) : 
            base(matrix.mxCreateString(value), mxArrayType.Char, 2, new int[]{1, value.Length}) {
            CheckActive();
        }

        public override string ToString() {
            IntPtr ptr = matrix.mxGetData(this.NativeObject);
            if(ptr == IntPtr.Zero)
                return string.Empty;

            byte[] buffer = new byte[this.Length * this.ElementSize];
            Marshal.Copy(ptr, buffer, 0, buffer.Length);
            return Encoding.Unicode.GetString(buffer);
        }

        public Array ToArray() {
            int m = this.M, n = this.N;
            char[] tmpch = new char[n];
            string[] strarray = new string[m];
            string str = this.ToString();

            for (int r = 0; r < m; r++) {
                for (int c = 0; c < n; c++) {
                    tmpch[c] = str[c * m + r];
                }

                strarray[r] = new string(tmpch);
            }

            return strarray;
        }
    }
}
